<?php

namespace App\WeChat\OAuth;

use App\WeChat\Contracts\WeChatOAuth;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;

class EasyWeChatOAuth implements WeChatOAuth
{
    protected $wechat;
    protected $wechatUser;

    public function __construct(Application $wechat)
    {
        $this->wechat = $wechat;
    }

    public function check()
    {       
        
        if(config('app.debug') && !$this->is_weixin()) {
            $wxUser = [
                'id'=>env('WX_TEST_OPENID','oUnI_uFQyhsbw9gu497qziB194Os'),
                'avatar'=> 'https://gss0.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D600%2C800/sign=58b9eb1c972397ddd62c900269b29e8f/562c11dfa9ec8a135ea6851bf103918fa1ecc089.jpg',
                'name'=>'虾米',
                'nickname'=>'虾米',
                'original'=>[
                    'sex'=>0
                ]

            ];
            session()->put('wechat_user',$wxUser);
        }
        $wxUser = session('wechat_user');
        return $wxUser && !empty($wxUser['id']);
    }

    public function authenticate(Request $request)
    {

        if(!$request->has('code')) {
            $url = $request->fullUrl();
            return $this->wechat->oauth->scopes(['snsapi_userinfo'])
                ->redirect($url);
        } else {
            $this->wechatUser = $this->wechat->oauth->user();
            session()->put('wechat_user',$this->wechatUser);
            return null;
        }
    }

    protected function is_weixin()
    {
        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }
}